package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.*;
import org.example.pojo.DStaff;
import org.example.pojo.DUniform;
import org.example.pojo.select.DUniformSelect;
import org.example.service.DUniformService;
import org.example.mapper.DUniformMapper;
import org.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.*;

/**
* @author chenhongkai
* @description 针对表【d_uniform】的数据库操作Service实现
* @createDate 2024-12-27 11:16:20
*/
@Service
public class DUniformServiceImpl extends ServiceImpl<DUniformMapper, DUniform>
    implements DUniformService {

    @Autowired
    private DUniformMapper dUniformMapper;

    @Override
    public Result<Map> selectAll(DUniformSelect dUniformSelect) {

        //分页查询
        Page<DStaff> page = new Page<>(dUniformSelect.getCurrentPage(), dUniformSelect.getPageSize());

        //关闭插件的count查询
        page.setSearchCount(false);
        Long staffsTotal = dUniformMapper.SelectAllUniforms_total(dUniformSelect);

        //自定义设置分页总数
        page.setTotal(staffsTotal);
        IPage<DUniform> mapIPage = dUniformMapper.SelectAllUniforms(page, dUniformSelect);

        Map uniformMap = new HashMap();
        uniformMap.put("uniform", mapIPage.getRecords());
        uniformMap.put("pageSize", mapIPage.getSize());
        uniformMap.put("pageTotal", mapIPage.getTotal());

        return Result.ok(uniformMap);
    }

    @Override
    public Result<Map> addUniform(DUniformSelect dUniformSelect) {
        for (DUniform uniform : dUniformSelect.getUniformList()) {
            int row = dUniformMapper.insert(uniform);
            if (row == 0) return Result.error("新增登记记录失败");
        }
        return Result.ok(null);
    }

    @Override
    public Result<Map> deleteUniform(DUniformSelect dUniformSelect) {
        System.out.println("dUniformSelect = " + dUniformSelect);
        DUniform dUniform = new DUniform();
        dUniform.setUfid(dUniformSelect.getUfid());
        dUniform.setIsDeleted(0);
        int row = dUniformMapper.updateById(dUniform);
        if (row == 0) return Result.error("逻辑删除失败");
        return Result.ok(null);
    }

    @Override
    public Result<Map> updateUniform(DUniform dUniform) {
        // 逻辑删除
        DUniform dUniformDel = new DUniform();
        dUniformDel.setUfid(dUniform.getUfid());
        dUniformDel.setIsDeleted(0);
        dUniformMapper.updateById(dUniformDel);
        // 重新新增
        dUniform.setUfid(null);
        dUniformMapper.insert(dUniform);
        return Result.ok(null);
    }

    @Override
    public Result<Map> uploadUniform(MultipartFile file) {
        try {
            // 检查文件是否为空
            if (file == null || file.isEmpty()) {
                return Result.error("上传文件为空");
            }
            // 获取文件输入流
            InputStream inputStream = file.getInputStream();
            // 创建工作簿
            Workbook workbook = WorkbookFactory.create(inputStream);
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);

            // 从第二行开始读取数据（跳过标题行）
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    DUniform uniform = new DUniform();
                    // 根据列索引读取数据（根据实际Excel结构调整）
                    if (row.getCell(0) != null) {
                        uniform.setCollectionDate((Date) getCellValue(row.getCell(0),Date.class));
                    }

                    if (row.getCell(1) != null) {
                        uniform.setEmpNo((String) getCellValue(row.getCell(1),String.class));
                    }
                    if (row.getCell(2) != null) {
                        uniform.setEmpName((String) getCellValue(row.getCell(2),String.class));
                    }
                    if (row.getCell(3) != null) {
                        uniform.setClothesSize((String) getCellValue(row.getCell(3),String.class));
                    }
                    if (row.getCell(4) != null) {
                        uniform.setClothesNumber((Integer) getCellValue(row.getCell(4),Integer.class));
                    }
                    if (row.getCell(5) != null) {
                        uniform.setClothesType((String) getCellValue(row.getCell(5),String.class));
                    }
                    if (row.getCell(6) != null) {
                        uniform.setClothesPrice((Double) getCellValue(row.getCell(6),Double.class));
                    }
                    if (row.getCell(7) != null) {
                        uniform.setHatColor((String) getCellValue(row.getCell(7),String.class));
                    }
                    if (row.getCell(8) != null) {
                        uniform.setHatNumber((Integer) getCellValue(row.getCell(8),Integer.class));
                    }
                    if (row.getCell(9) != null) {
                        uniform.setHatPrice((Double) getCellValue(row.getCell(9),Double.class));
                    }
                    if (row.getCell(10) != null) {
                        uniform.setAmount((Double) getCellValue(row.getCell(10),Double.class));
                    }
                    // 添加到数据库
//                    dUniformMapper.insert(uniform);
                    System.out.println("uniform = " + uniform);
                }
            }

            // 关闭资源
            workbook.close();
            inputStream.close();

            return Result.ok(null);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("文件解析失败: " + e.getMessage());
        }
    }


    // 辅助方法：根据需要的类型获取单元格值
    private Object getCellValue(Cell cell, Class<?> targetType) {
        if (cell == null) {
            return null;
        }

        switch (cell.getCellType()) {
            case STRING:
                if (targetType == String.class) {
                    return cell.getStringCellValue();
                } else if (targetType == Integer.class) {
                    try {
                        return Integer.parseInt(cell.getStringCellValue());
                    } catch (NumberFormatException e) {
                        return null;
                    }
                }
                break;

            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    if (targetType == Date.class) {
                        return cell.getDateCellValue();
                    } else if (targetType == String.class) {
                        return cell.getDateCellValue().toString();
                    }
                } else {
                    if (targetType == Integer.class) {
                        return (int) cell.getNumericCellValue();
                    } else if (targetType == String.class) {
                        return String.valueOf((long) cell.getNumericCellValue());
                    }
                }
                break;

            case BOOLEAN:
                if (targetType == Boolean.class) {
                    return cell.getBooleanCellValue();
                } else if (targetType == String.class) {
                    return String.valueOf(cell.getBooleanCellValue());
                }
                break;

            default:
                return null;
        }
        return null;
    }
}





